--[[
/*
 * Copyright (c) 2012 OptiCare Systems Ltd
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * Authors: Kevin Martin (kev82@khn.org.uk)
 */
]]
local function getResponseCode(response)
	local valid = {}
	valid["200"] = 1
	valid["201"] = 1
	valid["204"] = 1
	valid["401"] = 1
	valid["404"] = 1
	local code = response:match("HTTP/1.1 (%d%d%d)")
	if valid[code] == nil then
		error("Invalid HTTP Response Code")
	end
	return tonumber(code)
end

local function responseOK(response)
	local code = getResponseCode(response)
	if code >= 200 and code < 300 then return true end
	return false
end

local function responseNotAuth(response)
	local code  = getResponseCode(response)
	return code == 401
end

local function responseNotFound(response)
	local code  = getResponseCode(response)
	return code == 404
end

local function responseNoContent(response)
	local code  = getResponseCode(response)
	return code == 204
end

local function getResponseHeaders(response)
	local headers = {}
	local headerString = response:match("[%g ]+\r\n([%g \r\n]+)\r\n\r\n") .. "\r\n"
	if headerString == nil then error("Couldn't find header") end
	for k, v in headerString:gmatch("([%a%d%-]+): ([%g ]+)\r\n") do
		if k == nil then
			error("Unparseable Header")
		end
		headers[k] = v
	end
	return headers
end

local function getResponseBody(response)
	return response:match("^[%g \r\n]+\r\n\r\n(.*)$")
end

return {
 getResponseCode=getResponseCode,
 responseOK=responseOK,
 responseNotAuth=responseNotAuth,
 responseNotFound=responseNotFound,
 responseNoContent=responseNoContent,
 getResponseHeaders=getResponseHeaders,
 getResponseBody=getResponseBody
}
